<template>

  <ContentWrap>
    <!-- 搜索栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="90px">
      <el-form-item label="图书名称" prop="name">
        <el-input v-model="queryParams.name" class="!w-240px" clearable placeholder="请输入图书名称"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="章节名称" prop="name">
        <el-input v-model="queryParams.title" class="!w-240px" clearable placeholder="请输入章节名称"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button @click="getP()">
          <Icon class="mr-5px" icon="ep:refresh" />
          返回
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column align="center" label="图书名称" prop="name" />
      <el-table-column align="center" label="章节名称">
        <template #default="scope">
          <!--          <el-button  link type="info" @click="details(scope.row)">-->
          <!--            {{ scope.row.title }} {{ scope.row.isNot }}-->
          <!--          </el-button>-->
          <el-button link type="info" v-if="scope.row.isNot === 0" @click="details(scope.row)">
            {{ scope.row.title }}
          </el-button>
          <el-button disabled link type='' v-if="scope.row.isNot === 1">
            {{ scope.row.title }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column :width="300" align="center" label="操作">
        <template #default="scope">
          <el-button v-hasPermi="['housing:add']" link type="primary" @click="openDetails(scope.row)">
            详情
          </el-button>
          <el-button v-hasPermi="['housing:add']" link type="primary" @click="updateForm(scope.row)">
            编辑
          </el-button>
          <el-button v-hasPermi="['housing:delete']"
                                link
                                type="danger"
                                @click="del(scope.row)">
            删除
          </el-button>
          <el-button v-if="scope.row.section==0" v-hasPermi="['housing:add']" link type="primary" @click="knowledgePointExtraction(scope.row)">
            知识点提取
          </el-button>
          <el-button v-if="scope.row.section==0" v-hasPermi="['housing:add']" link type="primary" @click="popup(scope.row)">
            知识体系提取
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo" :total="total"
      @pagination="getList" />
  </ContentWrap>

  <Detail ref="openFormRef" />
  <Alter ref="openUpdateFormRef" />

  <!-- 知识体系提取弹窗 -->
  <el-dialog v-model="flage" title="知识体系提取" width="500" :before-close="handleClose">
    <el-form ref="ruleFormRef" :rules="rules" label-width="auto" :model="datatop" style="max-width: 800px">
      <el-form-item label="上级知识体系" prop="region">
        <el-tree-select v-model="datatop.id" :data="lants" :props="defaultProps" check-strictly default-expand-all
          placeholder="知识体系上级" value-key="id" />
      </el-form-item>
      <el-form-item label="知识体系名称" prop="name">
        <el-input v-model="datatop.name" />
      </el-form-item>
      <el-form-item label="知识体系编号" prop="code">
        <el-input v-model="datatop.code" :disabled="true"/>
      </el-form-item>
      <el-form-item label="显示排序" prop="sort">
        <el-input-number v-model="datatop.sort" :min="0" controls-position="right" />
      </el-form-item>
      <el-form-item>
        <el-button class='button' type="primary" @click="confirm(ruleFormRef)">确定</el-button>
        <el-button class='button1' type="danger" @click="flage=false">取消</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <!-- <div class="dialog-footer">
        <el-button type="primary" @click="flage = false">确定</el-button>
        <el-button @click="flage = false">
          取消
        </el-button>
      </div> -->
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import * as DebrisAPI from '@/api/debris'
import { useRouter, useRoute } from 'vue-router'
import Detail from './detail.vue'
import Alter from './alterForm.vue'
import * as NotifyTemplateApi from "@/api/system/notify/template";
import {ElMessageBox, ElNotification, inputEmits} from 'element-plus'
import { remove, inquiry, editor } from '@/api/knowledgeSystem/system'
import { defaultProps, handleTree } from '@/utils/tree'
import { FormInstance, FormRules, ElMessage } from 'element-plus'

//知识提取弹窗
const popup=(row: NotifyTemplateApi.NotifyTemplateVO)=>{
  datatop.name=row.title
  flage.value=true
}
interface RuleForm {
    id?: String,
    name: String,
    code: String,
    pid: Number,
    remark?: string,
    sort: Number,
    hasChildren?: boolean
    children?: RuleForm[]
}
interface Tree {
    label: string
    children?: Tree[]
}
const lists = () => {
  return {
    name: "",
    code: "",
    pid: 0,
    sort: 0
  }
}
const datatop = reactive<RuleForm>(lists())
//表单效验
const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
  ],
  // code: [
  //   { required: true, message: '请输入编号', trigger: 'blur' },
  // ],
})
const lants = ref([])
const data = ref<Tree[]>([
])
const arr = async () => {
  let listdata = await inquiry()
  console.log(listdata, 'listdata');
  data.value = handleTree(listdata)
  lants.value = data.value
}
arr()
const flage = ref(false)
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定要关闭窗口吗?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}
const ruleFormRef = ref<FormInstance>()
//点击确定按钮实现添加或者修改
const confirm = async () => {
  await ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      console.log(data.value, 'data')
      const res = data.value.filter((item) => item.name === datatop.name)
      if (!res.length || datatop.id) {
        console.log(flage.value);
        if (flage.value) {
          datatop.pid = datatop.id
        }
        delete datatop.id
        editor(datatop).then(result => {
          console.log(datatop.id)
          if (result) {
            ElMessage({
              type: "success",
              message: datatop.id ? '修改成功' : '添加成功'
            });
            arr()
            flage.value=true
            // clearForm()
          } else {
            ElMessage({
              type: "error",
              message: datatop.id ? '修改失败' : '添加失败'
            });
          }
        });
      } else {
        console.log('重复')
      }
    } else {
      // 表单验证失败，提示用户
      ElMessage.error('请填写正确的表单信息');
    }
  });
}
const router = useRouter()
const route = useRoute()
const message = useMessage()
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据

const formRef = ref<any>()

const queryFormRef = ref()

const showPreviewDialogFlag = ref(false)

const formJson = ref({
  widgetList: [],
  formConfig: {}
})

const details = async (row) => {
  loading.value = true
  try {
    queryParams.isbn = row.isbn
    queryParams.part = row.part
    queryParams.chapter = row.chapter
    queryParams.section = row.section
    queryParams.pid = row.pid
    queryParams.name = row.name
    queryParams.title = null
    queryParams.pageNo = 1;
    queryParams.pageSize = 10;
    const data = await DebrisAPI.one(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
// 知识点提取
const knowledgePointExtraction = async (row) => {
  console.log(row)
  const params = reactive({
    chapter: row.chapter,
    isbn: row.isbn,
  })
  localStorage.setItem('params', JSON.stringify(params))
  //调用知识点接口
  const Pullas = await DebrisAPI.Dropinterface(params)
  sessionStorage.setItem('Pullas', JSON.stringify(Pullas))
  console.log(Pullas, 'ass');
  router.push({
    name: 'extractManagement',
    // query: params,
  })
}
const queryParams = reactive({
  id: undefined,
  name: undefined,
  isbn: undefined,
  part: undefined,
  chapter: 0,
  section: 0,
  pid: ref([]),
  title: undefined,
  content: undefined,
  pageNo: 1,
  pageSize: 10
})
const handleQuery = () => {
  getList()
}
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
const star=ref(null)
const getList = async () => {
  loading.value = true
  try {
    const data = await DebrisAPI.page(queryParams)
    list.value = data.list
    list.value.forEach((item)=>{
      datatop.name=item.title
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const getP = async () => {
  loading.value = true
  try {
    if (queryParams.pid != null && queryParams.pid.length > 0) {
      // if (queryParams.pid.length == 1) {
      //   queryParams.pid = [];
      // }
      queryParams.pid.pop();
    } else if (queryParams.section > 0) {
      queryParams.section = 0
    } else if (queryParams.chapter > 0) {
      queryParams.isbn = null
      queryParams.part = null
      queryParams.chapter = 0
    }
    queryParams.pageNo = 1;
    queryParams.pageSize = 10;
    const data = await DebrisAPI.one(queryParams);
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 详情 */
const openFormRef = ref()
const openDetails = (row: NotifyTemplateApi.NotifyTemplateVO) => {
  openFormRef.value.open(row)
}
/** 添加/修改操作 */
const openUpdateFormRef = ref()
const updateForm = (row: NotifyTemplateApi.NotifyTemplateVO) => {
  openUpdateFormRef.value.open(row)
}
const del = async (row: NotifyTemplateApi.NotifyTemplateVO) => {
  try {
    await message.confirm('确定删除该条数据吗？')
    const data = row as DebrisAPI.BookDebrisPageReqVO
    await DebrisAPI.del(data)
    await getList()
    ElNotification({
      title: 'Success',
      message: '删除成功',
      type: 'success',
    })
  } catch {}
}

provide('getList', getList)

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
<style scoped>
.button{
  margin-bottom: -20%;
  margin-left: 35%
}
.button1{
  margin-bottom: -20%
}
</style>
